package com.s63.dao;

import com.s63.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(User user) {
        return jdbcTemplate.update("INSERT INTO `t_user` (`account`, `real_name`, `password`, " +
                        "`sex`, `birthday`, `mobile`, `address`, `role_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                user.getAccount(), user.getRealName(), user.getPassword(),
                user.getSex(), user.getBirthday(), user.getMobile(), user.getAddress(), user.getRoleId());
    }

    @Override
    public int del(Integer id) {
        return jdbcTemplate.update("DELETE FROM t_user WHERE id = ?", id);
    }

    @Override
    public int update(User user) {
        return jdbcTemplate.update("UPDATE `t_user` SET `account`=?, `real_name`=?, `password`=?, " +
                        "`sex`=?, `birthday`=?, `mobile`=?, `address`=?, `role_id`=? WHERE id =?",
                user.getAccount(), user.getRealName(), user.getPassword(),
                user.getSex(), user.getBirthday(), user.getMobile(), user.getAddress(), user.getRoleId(), user.getId());
    }

    @Override
    public User getById(Integer id) {
        return jdbcTemplate.queryForObject("select * from t_user where id = ?", new BeanPropertyRowMapper<>(User.class), id);
    }

    @Override
    public List<User> getAll() {
        return jdbcTemplate.query("select * from t_user", new BeanPropertyRowMapper<>(User.class));
    }
}
